
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/icon_names.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/result_data.dart';
import 'package:smart_freezer/core/utils/local_storage.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/core/view/agreement_widget.dart';
import 'package:smart_freezer/core/view/lc_fullscreen_widget.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';
import 'package:ty_smart_home/ty_smart_home.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  TextEditingController _emailController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();

  @override
  void initState() {
    super.initState();

    _emailController.text = LocalStorage.getAccount(); // "string@qq.com";
    _pwdController.text = LocalStorage.getPassword();  // "string";

    LocalStorage.setIsLogin(false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
            child: LCFullScreen(child: Image.asset(IconNames.login_bg, fit: BoxFit.fill, )),
          ),

          Positioned(
            top: 110,
            child: Image.asset(IconNames.login_logo, width: MainCommon.screenWidth * 0.55,)
          ),

          Container(
            margin: EdgeInsets.fromLTRB(50, 200 + 110, 50, 0),
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    children: [
                      SizedBox(height: 10,),
                      TextField(
                        controller: _emailController,
                        decoration: InputDecoration(
                          hintText: "Email",
                          contentPadding: EdgeInsets.symmetric(horizontal: 10),  // TF宽高间距
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(color: Colors.grey, width: 1),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(color: Colors.grey, width: 1),
                          ),
                          filled: true,
                          fillColor: Color(0xFF3E3A39),
                          hintStyle: TextStyle(color: Colors.grey),
                        ),
                        style: TextStyle(color: Colors.grey),
                        cursorColor: Colors.grey,
                        onSubmitted: (value) {
                          print("onSubmitted:$value");
                        },
                      ),
                      SizedBox(height: 10,),
                      TextField(
                        controller: _pwdController,
                        decoration: InputDecoration(
                          hintText: "Password",
                          contentPadding: EdgeInsets.symmetric(horizontal: 10),  // TF宽高间距
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(color: Colors.grey, width: 1),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(color: Colors.grey, width: 1),
                          ),
                          filled: true,
                          hintStyle: TextStyle(color: Colors.grey),
                          fillColor: Color(0xFF3E3A39),
                        ),
                        style: TextStyle(color: Colors.grey),
                        cursorColor: Colors.grey,
                        obscureText: true,
                        onSubmitted: (value) {
                          print("onSubmitted:$value");
                        },
                      ),

                      SizedBox(height: 20,),

                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          InkWell(
                            onTap: () {
                              Get.toNamed(LCRouter.login_forget);
                            },
                            child: Container(
                              width: 70,
                              child: Text(
                                  LocaleKeys.login_forget_pwd.trc(),
                                  style: TextStyle(color: Colors.white, decoration: TextDecoration.underline,),
                                  maxLines: 2, overflow: TextOverflow.ellipsis
                              ),
                              alignment: Alignment.center,
                            ),
                          ),
                          InkWell(
                              onTap: () {  // 登录
                                _startLogin();
                              },
                              child: Image.asset(IconNames.login_go, width: 60,)
                          ),
                          InkWell(
                            onTap: () {
                              Get.toNamed(LCRouter.login_register);
                            },
                            child: Container(
                              width: 70,
                              child: Text(LocaleKeys.login_register.trc(), style: TextStyle(color: Colors.white, decoration: TextDecoration.underline,)),
                              alignment: Alignment.centerRight,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),

                  Container(
                    margin: EdgeInsets.fromLTRB(0, 150, 0, 0),
                    child: Image.asset(IconNames.login_logo02, width: 100,),
                  ),

                ],
              ),
            ),
          ),

        ],
      ),
    );
  }

  _startLogin() async {
    if(_emailController.text.isEmpty) {
      SmartDialog.showToast("${LocaleKeys.other_email.trc()}${LocaleKeys.other_no_data.trc()}");
      return;
    }
    if(_pwdController.text.isEmpty) {
      SmartDialog.showToast("${LocaleKeys.other_password.trc()}${LocaleKeys.other_no_data.trc()}");
      return;
    }

    final params = {"email": _emailController.text, "password": _pwdController.text};
    ResultData data = await AppApi.getInstance().startLogin(params);
    if(data.code == 0){  // 请求成功
      final token = data.data["token"].toString();
      final roles = data.data["roles"].toString();  // 角色: 1-厨师, 2-技术人员, 3-工程经理
      final id = data.data["id"].toString();
      LocalStorage.setToken(token);
      LocalStorage.setRole(roles);

      Get.offNamed(LCRouter.home);
      LocalStorage.setIsLogin(true);

      /// 记住账号和密码
      LocalStorage.setAccount(_emailController.text);
      LocalStorage.setPassword(_pwdController.text);

      /// 设置极光推送Id
      _saveRegisterId();

      // return;

      // final deviceInfo = await (DeviceInfoPlugin().androidInfo);
      // final releaseVersion = deviceInfo.version.release ?? "";
      // if(Platform.isAndroid && releaseVersion.compareTo("12") >= 0) return;   // Android12 不兼容

      // 开始涂鸦登录
      TySmartHome.loginOrRegisterWithUid("86", id, id).then((value) {
        if(value["result"] == "1"){  // 登录成功
          final tyUID = value["uid"];
          LocalStorage.setTyUID(tyUID!);
        }
        logs("涂鸦登录结果: $value");

      });

      // TySmartHome.loginApp("86", "13396075193", "15071196344").then((value) {
      //   if(value == "1"){
      //     LocalStorage.setTyUID("13396075193" + "15071196344");
      //   }
      //   logs("涂鸦登录结果: $value");
      // });




    }else{
      SmartDialog.showToast(data.msg);
    }
  }

  _saveRegisterId() async {
    final params = {
      "registrationId": LocalStorage.getRegisterID(),
      "languages": LocalStorage.getLanguageValue().toString()
    };
    ResultData data = await AppApi.getInstance().saveRegisterId(params);
    if(data.code == 0){

    }else{
      SmartDialog.showToast(data.msg);
    }
  }

}
